package com.lean.plugin

import com.android.build.api.dsl.ApplicationExtension
import com.android.build.api.variant.AndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.support.uppercaseFirstChar

class AdConfigPlugin : Plugin<Project> {

    companion object {
        private const val TASK_GROUP_NAME = "AdConfigPlugin"
    }

    override fun apply(project: Project) {
        val adConfig = project.extensions.create("adConfig", AdConfigExtensions::class.java)
        adConfig.fileName.convention("ad.properties")
        adConfig.firstDimension.convention("lean") //默认

        val flavorAppIdMap = mutableMapOf<String, String>()
        val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)

        androidComponents.finalizeDsl { extension ->
            if (extension is ApplicationExtension) {
                extension.productFlavors.asMap.forEach { t, applicationProductFlavor ->
                    println("product flavor key $t , name ${applicationProductFlavor.name},  appId ${applicationProductFlavor.applicationId}")
                    val appId = applicationProductFlavor.applicationId
                    if (!appId.isNullOrEmpty()) {
                        flavorAppIdMap[t] = appId
                    }
                }
            }
        }

        androidComponents.beforeVariants { variant ->
            val realFlavorName = variant.productFlavors.firstOrNull {
                it.first == adConfig.firstDimension.get()
            }?.second


            if (!realFlavorName.isNullOrEmpty()) { //create tasks.
                val taskName = "syncAdConfig${realFlavorName.uppercaseFirstChar()}"

                val applicationId = flavorAppIdMap[realFlavorName]
                if (!applicationId.isNullOrEmpty()) {
                    try {
                        project.tasks.getByName(taskName)
                    } catch (e: Exception) {
                        val destFile =
                            project.projectDir.resolve("src/${realFlavorName}/assets/${adConfig.fileName.get()}")
                        destFile.parentFile.mkdirs()
                        println("Create task $taskName for app $applicationId with flavor $realFlavorName, properties file with store at ${destFile.absolutePath}")
                        val adConfigTask = project.tasks.register<FetchAdConfigTask>(taskName) {
                            this.group = TASK_GROUP_NAME
                            this.baseUrl.set(adConfig.baseUrl)
                            this.applicationId.set(applicationId)
                            this.destPropertyFile.set(destFile)
                        }

                        adConfigTask.get().action()

                    }
                }
            }
        }
    }
}